from flask import Flask
from app.config import config_dict
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_socketio import SocketIO
from flask_mail import Mail

db = SQLAlchemy()
migrate = Migrate()
socket_io = SocketIO()
mail = Mail()


def create_app(config: str):
    app = Flask(__name__)
    app.config.from_object(config_dict[config])

    register_db(app, db)
    register_migrate(app, db, migrate)
    register_socketio(app, socket_io)
    register_mail(app, mail)

    from app.blueprint.BL_index import index_bl
    app.register_blueprint(index_bl)
    from app.blueprint.BL_socket import socket_bl
    app.register_blueprint(socket_bl)
    from app.blueprint.BL_sendmail import sendmail_bl
    app.register_blueprint(sendmail_bl)

    @app.route('/test')
    def __test():
        return "test route!"

    @app.shell_context_processor
    def add_shell_value():
        from app.datamodels.testdb import User, Role, Limit
        return dict(db=db, User=User, Role=Role, Limit=Limit)

    @app.context_processor
    def add_template_shell():
        return dict(test="hello world")

    return app


def register_mail(app, mail):
    mail.init_app(app)


def register_db(app, db):
    db.init_app(app)


def register_migrate(app, db, migrate):
    migrate.init_app(app, db)


def register_socketio(app, socket_io):
    socket_io.init_app(app)
